package com.kws.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kws.common.core.enums.ModelOpType;
import com.kws.common.core.sys.Ksys;
import com.kws.common.core.utils.KConstants;
import com.kws.common.core.utils.StringUtils;
import com.kws.common.core.utils.bean.BeanUtils;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.system.api.domain.SysUser;
import com.kws.system.domain.SysMessageManage;
import com.kws.system.domain.info.QueryMessageNotificationInfo;
import com.kws.system.domain.info.QueryMessageUserInfo;
import com.kws.system.domain.vo.CreateMessageNotificationRq;
import com.kws.system.domain.vo.QueryMessageUserRq;
import com.kws.system.domain.vo.UpdateMessageNotificationRq;
import com.kws.system.feign.ExpressDeliveryService;
import com.kws.system.mapper.SysMessageManageMapper;
import com.kws.system.service.SysMessageManageService;
import com.kws.system.service.SysMessageRemindService;
import com.kws.system.service.SysUserMessageService;
import com.kws.system.util.SendMailUtil;
import org.apache.ibatis.annotations.Update;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <b>SysMessageManageServiceImpl</b>
 *
 * @description: SysMessageManageServiceImpl <br>
 * @date: 2024/11/5 14:59 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class SysMessageManageServiceImpl extends ServiceImpl<SysMessageManageMapper, SysMessageManage> implements SysMessageManageService {
    private static final Logger logger = LoggerFactory.getLogger(SysMessageManageServiceImpl.class);

    @Autowired
    private SysUserMessageService sysUserMessageService;

    @Autowired
    private SysMessageRemindService sysMessageRemindService;

    @Autowired
    private ExpressDeliveryService expressDeliveryService;

    @Autowired
    private SendMailUtil sendMailUtil;

    @Override
    public Page<QueryMessageNotificationInfo> queryMessageNotificationPage(Integer pageNum, Integer pageSize, String messageName) {
        List<QueryMessageNotificationInfo> resultList = new ArrayList<>();
        Page<SysMessageManage> page = new Page<>(pageNum, pageSize);
        Page<SysMessageManage> pageInfo = baseMapper.queryMessageNotificationPage(page,messageName);
        if (CollectionUtil.isNotEmpty(pageInfo.getRecords())){
            pageInfo.getRecords().forEach(item -> {
                QueryMessageNotificationInfo sysMessageManage = new QueryMessageNotificationInfo();
                sysMessageManage.setId(item.getId());
                sysMessageManage.setMessageType(item.getMessageType());
                sysMessageManage.setMessageName(item.getMessageName());
                sysMessageManage.setMessageContent(item.getMessageContent());
                if (item.getUserIdentity().equals("-1")){
                    sysMessageManage.setNotificationUserType("全员");
                }else {
                    sysMessageManage.setNotificationUserType("部分人员");
                }
                if (StringUtils.isNotEmpty(item.getNotificationMode())) {
                    sysMessageManage.setNotificationMode(queryNotificationMode(item.getNotificationMode()));
                }

                sysMessageManage.setCreateUser(item.getCreateUser());
                sysMessageManage.setCreateTime(item.getCreateTime());
                resultList.add(sysMessageManage);
            });
        }
        Page<QueryMessageNotificationInfo> resultPageInfo = new Page<>();
        BeanUtil.copyProperties(pageInfo,resultPageInfo);
        resultPageInfo.setRecords(resultList);
        return resultPageInfo;
    }

    @Transactional
    @Override
    public boolean createMessageNotification(CreateMessageNotificationRq rq) {
        SysMessageManage sysMessageManage = new SysMessageManage();
        sysMessageManage.setMessageType(rq.getMessageType());
        sysMessageManage.setMessageName(rq.getMessageName());
        sysMessageManage.setMessageContent(rq.getMessageContent());
        if (CollectionUtil.isEmpty(rq.getUserIds())){
            sysMessageManage.setUserIdentity("-1");
        }else {
            sysMessageManage.setUserIdentity("0");
        }
        if (CollectionUtil.isNotEmpty(rq.getNotificationModeList())){
            String notificationMode = rq.getNotificationModeList().get(0);
            for (int i = 1; i < rq.getNotificationModeList().size(); i++) {
                notificationMode = notificationMode + ","+rq.getNotificationModeList().get(i);
            }
            sysMessageManage.setNotificationMode(notificationMode);
        }
        Ksys.setBasicModelData(sysMessageManage, SecurityUtils.getStringUserId(), KConstants.DATA_ENABLE, ModelOpType.CREATE);
        int insert = baseMapper.insert(sysMessageManage);
        if (1 == insert){
            if (CollectionUtil.isNotEmpty(rq.getUserIds())){
                sysUserMessageService.createMessageUser(rq.getUserIds(),sysMessageManage.getId(),"create");
            }
            return true;
        }
        return false;
    }

    @Override
    public QueryMessageNotificationInfo queryMessageNotificationById(Long id) {
        SysMessageManage sysMessageManage = baseMapper.selectById(id);
        if (null != sysMessageManage){
            QueryMessageNotificationInfo info = new QueryMessageNotificationInfo();
            info.setId(sysMessageManage.getId());
            info.setMessageType(sysMessageManage.getMessageType());
            info.setMessageName(sysMessageManage.getMessageName());
            info.setMessageContent(sysMessageManage.getMessageContent());
            if (sysMessageManage.getUserIdentity().equals("-1")){
                info.setNotificationUserType("全员");
            }else {
                info.setNotificationUserType("部分人员");
            }

            info.setNotificationMode(queryNotificationMode(sysMessageManage.getNotificationMode()));

            info.setCreateUser(sysMessageManage.getCreateUser());
            info.setCreateTime(sysMessageManage.getCreateTime());
            return info;
        }
        return null;
    }

    @Override
    public boolean updateMessageNotification(UpdateMessageNotificationRq rq) {
        SysMessageManage sysMessageManage = baseMapper.selectById(rq.getId());
        if (null != sysMessageManage){
            sysMessageManage.setMessageType(rq.getMessageType());
            sysMessageManage.setMessageName(rq.getMessageName());
            sysMessageManage.setMessageContent(rq.getMessageContent());
            if (CollectionUtil.isEmpty(rq.getUserIds())){
                sysMessageManage.setUserIdentity("-1");
            }else {
                sysMessageManage.setUserIdentity("0");
                sysUserMessageService.createMessageUser(rq.getUserIds(),rq.getId(),"update");
            }
            if (CollectionUtil.isNotEmpty(rq.getNotificationModeList())){
                String notificationMode = rq.getNotificationModeList().get(0);
                for (int i = 1; i < rq.getNotificationModeList().size(); i++) {
                    notificationMode = notificationMode + ","+rq.getNotificationModeList().get(i);
                }
                sysMessageManage.setNotificationMode(notificationMode);
            }
            Ksys.setBasicModelData(sysMessageManage,SecurityUtils.getStringUserId(),KConstants.DATA_ENABLE,ModelOpType.UPDATE);
            int i = baseMapper.updateById(sysMessageManage);
            if (1 == i){
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean deleteMessageNotificationById(Long id) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("enable","0");
        updateWrapper.set("update_user",SecurityUtils.getStringUserId());
        updateWrapper.set("update_time",new Date());
        int update = baseMapper.update(null, updateWrapper);
        if (1 == update){
            return true;
        }
        return false;
    }

    @Override
    public boolean releaseMessageNotificationById(Long id) {
        SysMessageManage sysMessageManage = baseMapper.selectById(id);
        if (null != sysMessageManage){
            if ("0".equals(sysMessageManage.getNotificationMode())){
                return sysMessageRemindService.createMessageRemind(sysMessageManage);
            }else if ("1".equals(sysMessageManage.getNotificationMode())){
                //查询用户信息
                List<SysUser> sysUserList = null;
                if ("-1".equals(sysMessageManage.getUserIdentity())) {
                    sysUserList = baseMapper.queryUserAll();
                }else {
                    sysUserList = baseMapper.queryUserByMessageId(sysMessageManage.getId());
                }
                if (CollectionUtil.isNotEmpty(sysUserList)){
                    sysUserList.forEach(item -> {
                        Map<String, String> map = new HashMap<>();
                        map.put("codeType","passCode");
                        map.put("phone",item.getPhonenumber());
                        map.put("code",sysMessageManage.getMessageContent());
                        expressDeliveryService.sendMsm(map);
                    });
                }

            }else if ("2".equals(sysMessageManage.getNotificationMode())){
                //查询用户信息
                List<SysUser> sysUserList = null;
                if ("-1".equals(sysMessageManage.getUserIdentity())) {
                    sysUserList = baseMapper.queryUserAll();
                }else {
                    sysUserList = baseMapper.queryUserByMessageId(sysMessageManage.getId());
                }

//                sendMailUtil()
            }
        }
        return false;
    }

    @Override
    public PageInfo<QueryMessageUserInfo> queryUserPage(QueryMessageUserRq rq) {
        SysMessageManage sysMessageManage = baseMapper.selectById(rq.getId());
        //根据消息提醒用户类型查询用户消息
        if (null != sysMessageManage &&"-1".equals(sysMessageManage.getUserIdentity())){
            PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
            List<QueryMessageUserInfo> messageUserList = baseMapper.queryUserNameAll(rq.getUserName());
            if (CollectionUtil.isNotEmpty(messageUserList)){
                messageUserList.forEach(item -> {
                    List<String> roleNameList = baseMapper.queryRoleNameList(item.getDeptId());
                    if (CollectionUtil.isNotEmpty(roleNameList)){
                        item.setRoleNameList(roleNameList);
                    }
                });
            }
            PageInfo<QueryMessageUserInfo> pageInfo = new PageInfo<>(messageUserList);
            return pageInfo;

        }else {
            PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
            List<QueryMessageUserInfo> messageUserList = baseMapper.queryMessageUser(rq.getUserName(),sysMessageManage.getId());
            if (CollectionUtil.isNotEmpty(messageUserList)){
                messageUserList.forEach(item -> {
                    List<String> roleNameList = baseMapper.queryRoleNameList(item.getDeptId());
                    if (CollectionUtil.isNotEmpty(roleNameList)){
                        item.setRoleNameList(roleNameList);
                    }
                });
            }
            PageInfo<QueryMessageUserInfo> pageInfo = new PageInfo<>(messageUserList);
            return pageInfo;
        }
    }

    @Override
    public SysMessageManage queryMessageManageById(long messageId) {
        return baseMapper.selectById(messageId);
    }

    public String queryNotificationMode(String notificationMode){
        String newNotificationMode = null;
        if (notificationMode.contains("0") && notificationMode.contains("1")){
            newNotificationMode = "站内通知、短信通知";
            return newNotificationMode;
        }else if (notificationMode.contains("0")){
            newNotificationMode = "站内通知";
            return newNotificationMode;
        }else if (notificationMode.contains("1")){
            newNotificationMode = "短信通知";
            return newNotificationMode;
        }
        return newNotificationMode;
    }
}
